{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Load your own PyTorch BERT model\n",
    "\n",
    "In the previous [example](https://github.com/deepjavalibrary/djl/blob/master/jupyter/BERTQA.ipynb), you run BERT inference with the model from Model Zoo. You can also load the model on your own pre-trained BERT and use custom classes as the input and output.\n",
    "\n",
    "In general, the PyTorch BERT model from [HuggingFace](https://github.com/huggingface/transformers) requires these three inputs:\n",
    "\n",
    "- word indices: The index of each word in a sentence\n",
    "- word types: The type index of the word.\n",
    "- attention mask: The mask indicates to the model which tokens should be attended to, and which should not after batching sequence together.\n",
    "\n",
    "We will dive deep into these details later."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Preparation\n",
    "\n",
    "This tutorial requires the installation of Java Kernel. To install the Java Kernel, see the [README](https://github.com/deepjavalibrary/djl/blob/master/jupyter/README.md)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There are dependencies we will use."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "// %mavenRepo snapshots https://oss.sonatype.org/content/repositories/snapshots/\n",
    "\n",
    "%maven ai.djl:api:0.12.0\n",
    "%maven ai.djl.pytorch:pytorch-engine:0.12.0\n",
    "%maven ai.djl.pytorch:pytorch-model-zoo:0.12.0\n",
    "%maven org.slf4j:slf4j-api:1.7.26\n",
    "%maven org.slf4j:slf4j-simple:1.7.26\n",
    "%maven net.java.dev.jna:jna:5.3.0\n",
    "        \n",
    "// See https://github.com/deepjavalibrary/djl/blob/master/pytorch/pytorch-engine/README.md\n",
    "// for more PyTorch library selection options\n",
    "%maven ai.djl.pytorch:pytorch-native-auto:1.8.1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Import java packages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import java.io.*;\n",
    "import java.nio.file.*;\n",
    "import java.util.*;\n",
    "import java.util.stream.*;\n",
    "\n",
    "import ai.djl.*;\n",
    "import ai.djl.ndarray.*;\n",
    "import ai.djl.ndarray.types.*;\n",
    "import ai.djl.inference.*;\n",
    "import ai.djl.translate.*;\n",
    "import ai.djl.training.util.*;\n",
    "import ai.djl.repository.zoo.*;\n",
    "import ai.djl.modality.nlp.*;\n",
    "import ai.djl.modality.nlp.qa.*;\n",
    "import ai.djl.modality.nlp.bert.*;"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Reuse the previous input**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "var question = \"When did BBC Japan start broadcasting?\";\n",
    "var resourceDocument = \"BBC Japan was a general entertainment Channel.\\n\" +\n",
    "    \"Which operated between December 2004 and April 2006.\\n\" +\n",
    "    \"It ceased operations after its Japanese distributor folded.\";\n",
    "\n",
    "QAInput input = new QAInput(question, resourceDocument);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Dive deep into Translator\n",
    "\n",
    "Inference in deep learning is the process of predicting the output for a given input based on a pre-defined model.\n",
    "DJL abstracts away the whole process for ease of use. It can load the model, perform inference on the input, and provide\n",
    "output. DJL also allows you to provide user-defined inputs. The workflow looks like the following:\n",
    "\n",
    "![https://github.com/deepjavalibrary/djl/blob/master/examples/docs/img/workFlow.png?raw=true](https://github.com/deepjavalibrary/djl/blob/master/examples/docs/img/workFlow.png?raw=true)\n",
    "\n",
    "The red block (\"Images\") in the workflow is the input that DJL expects from you. The green block (\"Images\n",
    "bounding box\") is the output that you expect. Because DJL does not know which input to expect and which output format that you prefer, DJL provides the `Translator` interface so you can define your own\n",
    "input and output.\n",
    "\n",
    "The `Translator` interface encompasses the two white blocks: Pre-processing and Post-processing. The pre-processing\n",
    "component converts the user-defined input objects into an NDList, so that the `Predictor` in DJL can understand the\n",
    "input and make its prediction. Similarly, the post-processing block receives an NDList as the output from the\n",
    "`Predictor`. The post-processing block allows you to convert the output from the `Predictor` to the desired output\n",
    "format."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Pre-processing\n",
    "\n",
    "Now, you need to convert the sentences into tokens. We provide a powerful tool `BertTokenizer` that you can use to convert questions and answers into tokens, and batchify your sequence together. Once you have properly formatted tokens, you can use `Vocabulary` to map your token to BERT index.\n",
    "\n",
    "The following code block demonstrates tokenizing the question and answer defined earlier into BERT-formatted tokens."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "var tokenizer = new BertTokenizer();\n",
    "List<String> tokenQ = tokenizer.tokenize(question.toLowerCase());\n",
    "List<String> tokenA = tokenizer.tokenize(resourceDocument.toLowerCase());\n",
    "\n",
    "System.out.println(\"Question Token: \" + tokenQ);\n",
    "System.out.println(\"Answer Token: \" + tokenA);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`BertTokenizer` can also help you batchify questions and resource documents together by calling `encode()`.\n",
    "The output contains information that BERT ingests.\n",
    "\n",
    "- getTokens: It returns a list of strings including the question, resource document and special word to let the model tell which part is the question and which part is the resource document. Because PyTorch BERT was trained with varioue sequence length, you don't pad the tokens.\n",
    "- getTokenTypes: It returns a list of type indices of the word to indicate the location of the resource document. All Questions will be labelled with 0 and all resource documents will be labelled with 1.\n",
    "\n",
    "    [Question tokens...DocResourceTokens...padding tokens] => [000000...11111....0000]\n",
    "    \n",
    "\n",
    "- getValidLength: It returns the actual length of the question and resource document tokens tokens, which are required  by MXNet BERT.\n",
    "- getAttentionMask: It returns the mask for the model to indicate which part should be paid attention to and which part is the padding. It is required by PyTorch BERT.\n",
    "\n",
    "    [Question tokens...DocResourceTokens...padding tokens] => [111111...11111....0000]\n",
    "    \n",
    "PyTorch BERT was trained with varioue sequence length, so we don't need to pad the tokens."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "BertToken token = tokenizer.encode(question.toLowerCase(), resourceDocument.toLowerCase());\n",
    "System.out.println(\"Encoded tokens: \" + token.getTokens());\n",
    "System.out.println(\"Encoded token type: \" + token.getTokenTypes());\n",
    "System.out.println(\"Valid length: \" + token.getValidLength());"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Normally, words and sentences are represented as indices instead of tokens for training. \n",
    "They typically work like a vector in a n-dimensional space. In this case, you need to map them into indices.\n",
    "DJL provides `Vocabulary` to take care of you vocabulary mapping.\n",
    "\n",
    "The bert vocab from Huggingface is of the following format.\n",
    "```\n",
    "[PAD]\n",
    "[unused0]\n",
    "[unused1]\n",
    "[unused2]\n",
    "[unused3]\n",
    "[unused4]\n",
    "[unused5]\n",
    "[unused6]\n",
    "[unused7]\n",
    "[unused8]\n",
    "...\n",
    "```\n",
    "We provide the `bert-base-uncased-vocab.txt` from our pre-trained BERT for demonstration."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "DownloadUtils.download(\"https://djl-ai.s3.amazonaws.com/mlrepo/model/nlp/question_answer/ai/djl/pytorch/bertqa/0.0.1/bert-base-uncased-vocab.txt.gz\", \"build/pytorch/bertqa/vocab.txt\", new ProgressBar());"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "var path = Paths.get(\"build/pytorch/bertqa/vocab.txt\");\n",
    "var vocabulary = SimpleVocabulary.builder()\n",
    "        .optMinFrequency(1)\n",
    "        .addFromTextFile(path)\n",
    "        .optUnknownToken(\"[UNK]\")\n",
    "        .build();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can easily convert the token to the index using `vocabulary.getIndex(token)` and the other way around using `vocabulary.getToken(index)`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "long index = vocabulary.getIndex(\"car\");\n",
    "String token = vocabulary.getToken(2482);\n",
    "System.out.println(\"The index of the car is \" + index);\n",
    "System.out.println(\"The token of the index 2482 is \" + token);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To properly convert them into `float[]` for `NDArray` creation, here is the helper function:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now that you have everything you need, you can create an NDList and populate all of the inputs you formatted earlier. You're done with pre-processing! \n",
    "\n",
    "#### Construct `Translator`\n",
    "\n",
    "You need to do this processing within an implementation of the `Translator` interface. `Translator` is designed to do pre-processing and post-processing. You must define the input and output objects. It contains the following two override classes:\n",
    "- `public NDList processInput(TranslatorContext ctx, I)`\n",
    "- `public String processOutput(TranslatorContext ctx, O)`\n",
    "\n",
    "Every translator takes in input and returns output in the form of generic objects. In this case, the translator takes input in the form of `QAInput` (I) and returns output as a `String` (O). `QAInput` is just an object that holds questions and answer; We have prepared the Input class for you."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Armed with the needed knowledge, you can write an implementation of the `Translator` interface. `BertTranslator` uses the code snippets explained previously to implement the `processInput`method. For more information, see [`NDManager`](https://javadoc.io/static/ai.djl/api/0.12.0/index.html?ai/djl/ndarray/NDManager.html).\n",
    "\n",
    "```\n",
    "manager.create(Number[] data, Shape)\n",
    "manager.create(Number[] data)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "public class BertTranslator implements Translator<QAInput, String> {\n",
    "    private List<String> tokens;\n",
    "    private Vocabulary vocabulary;\n",
    "    private BertTokenizer tokenizer;\n",
    "    \n",
    "    @Override\n",
    "    public void prepare(NDManager manager, Model model) throws IOException {\n",
    "        Path path = Paths.get(\"build/pytorch/bertqa/vocab.txt\");\n",
    "        vocabulary = SimpleVocabulary.builder()\n",
    "                    .optMinFrequency(1)\n",
    "                    .addFromTextFile(path)\n",
    "                    .optUnknownToken(\"[UNK]\")\n",
    "                    .build();\n",
    "        tokenizer = new BertTokenizer();\n",
    "    }\n",
    "    \n",
    "    @Override\n",
    "    public NDList processInput(TranslatorContext ctx, QAInput input) {\n",
    "        BertToken token =\n",
    "                tokenizer.encode(\n",
    "                        input.getQuestion().toLowerCase(),\n",
    "                        input.getParagraph().toLowerCase());\n",
    "        // get the encoded tokens that would be used in precessOutput\n",
    "        tokens = token.getTokens();\n",
    "        NDManager manager = ctx.getNDManager();\n",
    "        // map the tokens(String) to indices(long)\n",
    "        long[] indices = tokens.stream().mapToLong(vocabulary::getIndex).toArray();\n",
    "        long[] attentionMask = token.getAttentionMask().stream().mapToLong(i -> i).toArray();\n",
    "        long[] tokenType = token.getTokenTypes().stream().mapToLong(i -> i).toArray();\n",
    "        NDArray indicesArray = manager.create(indices);\n",
    "        NDArray attentionMaskArray =\n",
    "               manager.create(attentionMask);\n",
    "        NDArray tokenTypeArray = manager.create(tokenType);\n",
    "        // The order matters\n",
    "        return new NDList(indicesArray, attentionMaskArray, tokenTypeArray);\n",
    "    }\n",
    "    \n",
    "    @Override\n",
    "    public String processOutput(TranslatorContext ctx, NDList list) {\n",
    "        NDArray startLogits = list.get(0);\n",
    "        NDArray endLogits = list.get(1);\n",
    "        int startIdx = (int) startLogits.argMax().getLong();\n",
    "        int endIdx = (int) endLogits.argMax().getLong();\n",
    "        return tokens.subList(startIdx, endIdx + 1).toString();\n",
    "    }\n",
    "    \n",
    "    @Override\n",
    "    public Batchifier getBatchifier() {\n",
    "        return Batchifier.STACK;\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Congrats! You have created your first Translator! We have pre-filled the `processOutput()` function to process the `NDList` and return it in a desired format. `processInput()` and `processOutput()` offer the flexibility to get the predictions from the model in any format you desire. \n",
    "\n",
    "With the Translator implemented, you need to bring up the predictor that uses your `Translator` to start making predictions. You can find the usage for `Predictor` in the [Predictor Javadoc](https://javadoc.io/static/ai.djl/api/0.12.0/index.html?ai/djl/inference/Predictor.html). Create a translator and use the `question` and `resourceDocument` provided previously."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "DownloadUtils.download(\"https://djl-ai.s3.amazonaws.com/mlrepo/model/nlp/question_answer/ai/djl/pytorch/bertqa/0.0.1/trace_bertqa.pt.gz\", \"build/pytorch/bertqa/bertqa.pt\", new ProgressBar());"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "BertTranslator translator = new BertTranslator();\n",
    "\n",
    "Criteria<QAInput, String> criteria = Criteria.builder()\n",
    "        .setTypes(QAInput.class, String.class)\n",
    "        .optModelPath(Paths.get(\"build/pytorch/bertqa/\")) // search in local folder\n",
    "        .optTranslator(translator)\n",
    "        .optProgress(new ProgressBar()).build();\n",
    "\n",
    "ZooModel model = criteria.loadModel();"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "String predictResult = null;\n",
    "QAInput input = new QAInput(question, resourceDocument);\n",
    "\n",
    "// Create a Predictor and use it to predict the output\n",
    "try (Predictor<QAInput, String> predictor = model.newPredictor(translator)) {\n",
    "    predictResult = predictor.predict(input);\n",
    "}\n",
    "\n",
    "System.out.println(question);\n",
    "System.out.println(predictResult);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Based on the input, the following result will be shown:\n",
    "```\n",
    "[december, 2004]\n",
    "```\n",
    "That's it! \n",
    "\n",
    "You can try with more questions and answers. Here are the samples:\n",
    "\n",
    "**Answer Material**\n",
    "\n",
    "The Normans (Norman: Nourmands; French: Normands; Latin: Normanni) were the people who in the 10th and 11th centuries gave their name to Normandy, a region in France. They were descended from Norse (\"Norman\" comes from \"Norseman\") raiders and pirates from Denmark, Iceland and Norway who, under their leader Rollo, agreed to swear fealty to King Charles III of West Francia. Through generations of assimilation and mixing with the native Frankish and Roman-Gaulish populations, their descendants would gradually merge with the Carolingian-based cultures of West Francia. The distinct cultural and ethnic identity of the Normans emerged initially in the first half of the 10th century, and it continued to evolve over the succeeding centuries.\n",
    "\n",
    "\n",
    "**Question**\n",
    "\n",
    "Q: When were the Normans in Normandy?\n",
    "A: 10th and 11th centuries\n",
    "\n",
    "Q: In what country is Normandy located?\n",
    "A: france\n",
    "\n",
    "For the full source code, see the [DJL repo](https://github.com/deepjavalibrary/djl/blob/master/examples/src/main/java/ai/djl/examples/inference/BertQaInference.java) and translator implementation [MXNet](https://github.com/deepjavalibrary/djl/blob/master/mxnet/mxnet-model-zoo/src/main/java/ai/djl/mxnet/zoo/nlp/qa/MxBertQATranslator.java) [PyTorch](https://github.com/deepjavalibrary/djl/blob/master/pytorch/pytorch-model-zoo/src/main/java/ai/djl/pytorch/zoo/nlp/qa/PtBertQATranslator.java)."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Java",
   "language": "java",
   "name": "java"
  },
  "language_info": {
   "codemirror_mode": "java",
   "file_extension": ".jshell",
   "mimetype": "text/x-java-source",
   "name": "Java",
   "pygments_lexer": "java",
   "version": "14.0.2+12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
